package com.wanban.adutils

import android.app.Activity
import android.app.Application
import android.util.Log
import com.facebook.ads.AdError
import com.facebook.ads.AdSettings
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.RequestConfiguration
import com.ironsource.mediationsdk.IronSource
import com.ironsource.mediationsdk.integration.IntegrationHelper
import com.unity3d.mediation.LevelPlay
import com.unity3d.mediation.LevelPlayConfiguration
import com.unity3d.mediation.LevelPlayInitError
import com.unity3d.mediation.LevelPlayInitListener
import com.unity3d.mediation.LevelPlayInitRequest
import com.wanban.adutils.db.AdRoomUtils
import com.wanban.adutils.db.bean.AdContent
import com.wanban.adutils.db.bean.AdInfo
import com.wanban.adutils.tools.AdConstants
import com.wanban.adutils.tools.RxUtils


object AdUtils {

    lateinit var appContext: Application
    var debugModel = false
    private var isUserDefaultAdPosition = true
    private var isCheckAd = false
    /**
     * 广告初始化
     */
    fun init(context: Application,
             ironSourceAppKey: String,
             isDebugModel: Boolean = false, isUserDefaultAdPosition: Boolean = true, isCheckAd: Boolean = false) {
        appContext = context
        debugModel = isDebugModel
        this.isCheckAd = isCheckAd
        this.isUserDefaultAdPosition = isUserDefaultAdPosition
        addTestDevices()
        // unity 欧盟同意和 GDPR
        initAdmob()
        initIronSource(context, ironSourceAppKey)
    }

    private fun initAdmob() {
        // unity 欧盟同意和 GDPR
        val requestConfiguration = MobileAds.getRequestConfiguration()
            .toBuilder()
            .setTagForChildDirectedTreatment(RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE)
            .setTagForUnderAgeOfConsent(RequestConfiguration.TAG_FOR_UNDER_AGE_OF_CONSENT_FALSE)
            .build()
        MobileAds.setRequestConfiguration(requestConfiguration)
        // Admob 初始化
        MobileAds.initialize(appContext)
    }


    /**
     * 更新广告信息
     */
    fun insertAds(ads: ArrayList<AdContent>) {
        val adDao = AdRoomUtils.getInstance().adDao()
        // 清空广告
        adDao.deleteAll()
        // 保存最新的广告
        adDao.insert(ads)
    }


    /**
     * 清空广告信息
     */
    fun clearAdCache() {
        AdRoomUtils.getInstance().adDao().deleteAll()
    }

    /**
     * 根据是否是debugModel获取对应广告商的广告ID
     */
    fun getUnitId(adInfo: AdInfo): String {
        val positionId = if (debugModel && isUserDefaultAdPosition) {
            if (adInfo.advertiser == AdConstants.ADVERTISER_ADMOB) {
                when (adInfo.ad_type) {
                    AdConstants.ADTYPE_BANNER -> "ca-app-pub-3940256099942544/6300978111"
                    AdConstants.ADTYPE_PAUSE_VIDEO -> "ca-app-pub-3940256099942544/2247696110"
                    AdConstants.ADTYPE_INSTREAM_VIDEO -> "ca-app-pub-3940256099942544/2247696110"
                    AdConstants.ADTYPE_REWARDED -> "ca-app-pub-3940256099942544/5224354917"
                    AdConstants.ADTYPE_INTERSTITIAL -> "ca-app-pub-3940256099942544/1033173712"
                    AdConstants.ADTYPE_OPEN -> "ca-app-pub-3940256099942544/2247696110"
                    // 测试中介
//                    AdConstants.ADTYPE_BANNER -> "ca-app-pub-6808984737303159/5621265609"
//                    AdConstants.ADTYPE_INTERSTITIAL -> "ca-app-pub-6808984737303159/2674703912"
//                    AdConstants.ADTYPE_PAUSE_VIDEO -> "ca-app-pub-6808984737303159/3507890542"
//                    AdConstants.ADTYPE_INSTREAM_VIDEO -> "ca-app-pub-6808984737303159/3507890542"
//                    AdConstants.ADTYPE_REWARDED -> "ca-app-pub-6808984737303159/2933175470"
                    AdConstants.ADTYPE_SPLASH -> "ca-app-pub-3940256099942544/3419835294"
                    else -> "ca-app-pub-3940256099942544/6300978111"
                }
            } else {
                when (adInfo.ad_type) {
                    AdConstants.ADTYPE_BANNER -> "5024158"
                    AdConstants.ADTYPE_PAUSE_VIDEO -> "5024158"
                    AdConstants.ADTYPE_INSTREAM_VIDEO -> "5024158"
                    AdConstants.ADTYPE_REWARDED -> "5958103"
                    AdConstants.ADTYPE_INTERSTITIAL -> "5024156"
                    AdConstants.ADTYPE_OPEN -> "5024158"
                    else -> "5024158"
                }
            }
        } else {
            adInfo.ad_position
        }
        if (debugModel) {
            Log.e(AdConstants.TAG, "positionId -> $positionId")
        }
        return positionId
    }



    /**
     * 获取Admob的AdRequest
     */
    fun getAdRequest(): AdRequest {
        val adRequestBuilder = AdRequest.Builder()
        return adRequestBuilder.build()
    }

    /**
     * 根据广告类型获的广告名称
     */
    fun getAdNameByType(adType: Long): String {
        return when(adType) {
            AdConstants.AD_ID_OPEN -> "开屏广告"
            AdConstants.AD_ID_OPEN_AD_V2 -> "新开屏广告"
            AdConstants.AD_ID_VIDEO_DETAIL_INTERSTITIAL -> "详情页插屏广告"
            AdConstants.AD_ID_VIDEO_DETAIL_PAUSE -> "详情页暂停广告"
            AdConstants.AD_ID_VIDEO_INSTREAM_AD -> "详情页插播广告"
            AdConstants.AD_ID_VIDEO_DETAIL_BANNER -> "详情页Banner广告"
            AdConstants.AD_ID_LOCK_REWARD_AD -> "解锁激励广告"
            AdConstants.AD_ID_LOCK_INTERSTITIAL_AD -> "解锁插屏广告"
            AdConstants.AD_ID_DOWNLOAD_REWARD_AD -> "下载激励广告"
            AdConstants.AD_ID_DOWNLOAD_INTERSTITIAL -> "下载插屏广告"
            AdConstants.AD_ID_REOPEN_AD -> "Reopen广告"
            else -> "未知"
        }
    }

    /**
     * 转换Facebook的错误代码
     */
    fun getFbErrorCode(errorCode: Int): Int {
        return when (errorCode) {
            AdError.NETWORK_ERROR_CODE -> AdConstants.ERROR_CODE_NETWORK_ERROR
            AdError.NO_FILL_ERROR_CODE -> AdConstants.ERROR_CODE_NO_FILL
            AdError.SERVER_ERROR_CODE -> AdConstants.ERROR_CODE_INTERNAL_ERROR
            AdError.INTERNAL_ERROR_CODE -> AdConstants.ERROR_CODE_INTERNAL_ERROR
            AdError.CACHE_ERROR_CODE -> AdConstants.ERROR_CODE_INTERNAL_ERROR
            AdError.MEDIATION_ERROR_CODE -> AdConstants.ERROR_CODE_INTERNAL_ERROR
            AdError.LOAD_TOO_FREQUENTLY_ERROR_CODE -> AdConstants.ERROR_CODE_INTERNAL_ERROR
            else -> AdConstants.ERROR_CODE_INVALID_REQUEST
        }
    }

    private fun addTestDevices() {
        if (debugModel) {
            val testDeviceIds = listOf(
                "B53B7E170565BA0164FE1579F2FE84E1",
                "4E0B508D75ED24EC25202750DE4EFCFC",
                "BB7376830A029AD4F32E096CF202D584",
                "585AB3C75F8A644E6F425845E59872CB"
            )
            val configuration =
                RequestConfiguration.Builder().setTestDeviceIds(testDeviceIds)
                    .build()
            MobileAds.setRequestConfiguration(configuration)

            // Facebook
            AdSettings.setDebugBuild(debugModel)
            AdSettings.setIntegrationErrorMode(AdSettings.IntegrationErrorMode.INTEGRATION_ERROR_CALLBACK_MODE)
            AdSettings.turnOnSDKDebugger(appContext)
            AdSettings.setTestMode(debugModel)
            AdSettings.addTestDevices(
                listOf(
                    "8CA5FEB50C1947767FA7A1873F72C378",
                    "9678B3F09CC750E4C23CEDD4C70F73CB",
                    "4E0B508D75ED24EC25202750DE4EFCFC"
                )
            )
        } else {
            AdSettings.clearTestDevices()
        }
    }


    fun onResume(activity: Activity) {
        IronSource.onResume(activity)
    }

    fun onPause(activity: Activity) {
        IronSource.onPause(activity)
    }


    fun testIronSource(activity: Activity) {
        IntegrationHelper.validateIntegration(activity)
    }

    fun initIronSource(context: Application, appKey: String) {
        // LevelPlay 的中介平台支持发布者将用户的同意选择传达给中介网络（对于受支持的网络）。
        IronSource.setConsent(true)
        // 美国隐私合规性  允许“出售”个人信息
        IronSource.setMetaData("do_not_sell","false")
        // 具有年龄限制的面向儿童的应用程序的用户级设置: 最终用户不是儿童
        IronSource.setMetaData("is_child_directed","false")
        IronSource.setMetaData("Facebook_IS_CacheFlag","ALL")
        // 设置日志
        IronSource.setAdaptersDebug(debugModel)
        // 以广告id为userId
        val advertisingId = IronSource.getAdvertiserId(context)
//        IronSource.setUserId(advertisingId)
        IronSource.shouldTrackNetworkState(context, true)

        // 测试套件
        if (isCheckAd) {
            IronSource.setMetaData("is_test_suite", "enable")
        }

        // Init the SDK when implementing the Multiple Ad Units Interstitial and Banner APIs, and Rewarded using legacy APIs
        val legacyAdFormats = listOf(LevelPlay.AdFormat.INTERSTITIAL, LevelPlay.AdFormat.REWARDED)
        val initRequest = LevelPlayInitRequest.Builder(appKey)
            .withLegacyAdFormats(legacyAdFormats)
            .withUserId(advertisingId)
            .build()
        LevelPlay.init(context, initRequest, object: LevelPlayInitListener {
            override fun onInitFailed(error: LevelPlayInitError) {
                //Recommended to initialize again
                RxUtils.timer(2000) {
                    initIronSource(context, appKey)
                }
            }
            override fun onInitSuccess(configuration: LevelPlayConfiguration) {
                //Create ad objects and load ads
                // 启动测试
                if (isCheckAd) {
                    IronSource.launchTestSuite(context)
                }
            }
        })


        // 广告sdk初始化
//        IronSource.init(activity, appKey, {
//            // 广告质量初始化
//            try {
//                // 启动测试
//                if (isCheckAd) {
//                    IronSource.launchTestSuite(activity)
//                }
//                val adQualityConfigBuilder = ISAdQualityConfig.Builder()
//                adQualityConfigBuilder.setTestMode(debugModel)
//                adQualityConfigBuilder.setLogLevel(ISAdQualityLogLevel.INFO)
//                val adQualityConfig = adQualityConfigBuilder.build()
//                IronSourceAdQuality.getInstance().initialize(activity, appKey, adQualityConfig)
//            } catch (e: Exception) {
//                e.printStackTrace()
//            }
//        }, IronSource.AD_UNIT.INTERSTITIAL, IronSource.AD_UNIT.REWARDED_VIDEO, IronSource.AD_UNIT.BANNER)
    }
}